﻿using Newtonsoft.Json;
using PIMS.DBModel;
using PIMS.WorkPlugin.EAS;
using PIMS.WorkPlugin.ORM;
using PIMS.WorkPlugin.Util.Config;
using PIMS.YongXiang;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;

namespace PIMS.YongXiang
{
    internal class EASHelperDebug
    {
        /// <summary>
        /// RSA密钥对 调试环境
        /// </summary>
        private static string pubKeyDebug = "<RSAKeyValue><Modulus>nwzv7mA2s+6qHrSLllLN4/iEkr7zTzXu7mS5nqadrefwl9QymeldfRaKyn6oQy6LaLEJXLl+oK3vwA6qdj0EGC5FLIgwqlBWzRVyuKhT9/ojEUPvT3fLOy2pHu75H2geWVXUGEkWpaciiR/ZAusBCXQJ9+HZ2A2IudHXJvoIJD8=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
        private static string priKeyDebug = "<RSAKeyValue><Modulus>nwzv7mA2s+6qHrSLllLN4/iEkr7zTzXu7mS5nqadrefwl9QymeldfRaKyn6oQy6LaLEJXLl+oK3vwA6qdj0EGC5FLIgwqlBWzRVyuKhT9/ojEUPvT3fLOy2pHu75H2geWVXUGEkWpaciiR/ZAusBCXQJ9+HZ2A2IudHXJvoIJD8=</Modulus><Exponent>AQAB</Exponent><P>7KAW2jsvmTZVAkKo0VzWtUwbtQIf/NtS8YiI1aJ37poXBXfF+kRD7kBzI+/0wFOATqlf4x4u7gKJvzMgLFmo/Q==</P><Q>rBLM0oFcOLVwF9jCWOmo+jvYC2iOIXol9IG6poMU7ot9BvrNxb1Fjq/3MH0GAceSaqeoXoGmb2SrZo/0u5NU6w==</Q><DP>Ii11X4wQ8fZRDQSH0cWxFXqqvdhSunkLX+uyp/jRjdsf3CBSrjVSAoW4m8Y6+dSVwcbhHLLtYF9pef5udTl2GQ==</DP><DQ>DI46n8mMnx6uFS9dzvsNt2SSeRKh/FNbXaHxqqC58EYBU3cNeLY80xKH6OPWgl67kki1gl/Xcx1XXF54rw8rDQ==</DQ><InverseQ>YjVAMvtsf0arBOYqz9SLJCGMSEVSJsa12DJLJ209wt0h1zacscLxnApmuPtEqyKgL7BTKrqP9U6/SXAKOvTUcA==</InverseQ><D>L7NKlfxHC6mtXa4aGwhUdWWIJRadlAkB0n9k5/7iVVC1aGOclWpWvngvQdHAlv1zk/9cZnG/V2My/y+m0fU0r61GBRHD/o09flRT94qxcX02jiBue5F/7rdaHkiOyWlieJCsbXpLWXoSNAggK0ZQybFwW3V7UGkQdGDDWDQT7mk=</D></RSAKeyValue>";

        private static string url = ConfigManager.AppSettings["easurl"].Value;
        private static string Uid = "123";
        private static string apiUrl
        {
            get
            {
                if(url.EndsWith("Debug"))
                {
                   return url;
                }                 
                return url + "Debug";
            }
        } 

        private static string PrivateKey
        {
            get
            {
                return priKeyDebug;
            }
        }
        private static string PublicKey
        {
            get
            {

                return pubKeyDebug;

            }
        }

        /// <summary>
        /// 2.38 获取包装批号接口
        /// </summary>
        /// "[{\"PACKAGENUMBER\":\"YX-A-24-210701/S4/致密料/围板箱/方硅芯\"},{\"PACKAGENUMBER\":\"YX-A-24-210701/S2/致密料/围板箱/方硅芯\"},{\"PACKAGENUMBER\":\"YX-A-24-210701/S3/YX03致密料/围板箱/方硅芯\"},{\"PACKAGENUMBER\":\"YX-A-24-210701/S2/YX03致密料/围板箱/方硅芯\"},{\"PACKAGENUMBER\":\"YX-A-24-210701/S2/疏松料/围板箱/方硅芯\"},{\"PACKAGENUMBER\":\"YX-A-24-210701/S3/致密料/围板箱/方硅芯\"}]"
        /// 无结果返回 []
        /// <param name="manufactureBatch">生产批号</param>
        public static string GetPackageBatch(string manufactureBatch = "YX-A-24-210701")
        {
            try
            {
                string action = "{\"fun\":\"GetPackageBatch\",\"prms\":{\"manufacturebatch\":\"" + manufactureBatch + "\"}}";
                string uid = "123";
                string token = GetToken();

                // 时间搓
                TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                long timespan = Convert.ToInt64(ts.TotalSeconds);
                string orgdata = action + uid + timespan + token;

                // 获取hash码
                string sign = RSAHelper.XMLSign(orgdata, PrivateKey);
                Dictionary<string, string> header = new Dictionary<string, string>();
                header.Add("uid", uid);
                header.Add("token", token);
                header.Add("timespan", timespan.ToString());
                header.Add("sign", sign);
                string result = HttpPost(header, apiUrl, action);
                return result;
            }
            catch (WebException we)
            {
                if (we.Response != null)
                {
                    Stream stream = we.Response.GetResponseStream();
                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                    string value = reader.ReadToEnd();
                    MessageBox.Show(value, "Ex");
                }
            }
            catch (Exception ex)
            {
                Exception src = ex.GetBaseException();
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
            return null;
        }

        /// <summary>
        /// 2.40 上传箱号信息
        /// </summary>
        /// "{\"msg\":\"\",\"data\":{},\"flage\":1}"
        /// 
        /// "{\"msg\":\"错误:null\\nCaused exception message is: JSONObject[\\\"detail\\\"] is not a JSONArray.\",\"flage\":0}"
        /// "{\"msg\":\"错误:null\\nCaused exception message is: null object\",\"flage\":0}"
        /// "{\"msg\":\"错误:null\\nCaused exception message is: 该箱号:X2C12021090001已存在!不能重复导入!\",\"flage\":0}"
        public static string Import_CartonInfo(string boxId)
        {
            CartonInfo cartonInfo = new CartonInfo();
            //能源科技公司编码YX.10.20
            //云南通威二期公司编码YX.10.22
            //内蒙通威硅能源公司编码YX.10.21
            cartonInfo.company = "YX.10.11"; 
            cartonInfo.billbizdate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            cartonInfo.cartonNumber = boxId;  //X2C12021090004
            //cartonInfo.lot = "g1"; //未确定要不要
            cartonInfo.packageline = ""; //非必填
            cartonInfo.detail = new List<string>();

            try
            {
                DataTable dtBox = SqlSugarHelper.QueryToDataTable<saveddata>(
                    string.Format("select * from tb_saveddata where uid='{0}'", boxId));
                DataTable dtBag = SqlSugarHelper.QueryToDataTable<saveddataBag>(
                    string.Format("select * from tb_saveddataBag where boxid='{0}'", boxId));

                if (dtBox.Rows.Count > 0)
                {
                    cartonInfo.carNumber = dtBox.Rows[0]["reserved6"].ToString().Trim(); //车号
                    if (string.IsNullOrEmpty(dtBox.Rows[0]["reserved2"].ToString().Trim())) //定制料信息
                        cartonInfo.specialInfo = dtBox.Rows[0]["reserved3"].ToString().Trim(); //客户单位
                    else
                        cartonInfo.specialInfo = dtBox.Rows[0]["reserved2"].ToString().Trim() + ";" //定制料信息
                                + dtBox.Rows[0]["reserved3"].ToString().Trim(); //客户单位
                    cartonInfo.materialcase = dtBox.Rows[0]["productName"].ToString().Trim().Replace("（", "(").Replace("）", ")").Replace(" ", ""); //型号
                    cartonInfo.material = dtBox.Rows[0]["reserved11"].ToString().Trim(); //物料编码
                    cartonInfo.particleSize = dtBox.Rows[0]["productMark"].ToString().Trim(); //粒径
                    cartonInfo.grossWeight = dtBox.Rows[0]["reserved1"].ToString().Trim(); //毛重 要求纯数字
                    cartonInfo.netWeight = dtBox.Rows[0]["weight"].ToString().Trim(); //净重 要求纯数字
                    cartonInfo.manufacturebatch = dtBox.Rows[0]["batchNo"].ToString().Trim(); //批号
                    cartonInfo.packageNumber = dtBox.Rows[0]["reserved5"].ToString().Trim(); //包装批次
                    if (cartonInfo.packageNumber.Contains("纸箱"))
                        cartonInfo.packageType = 1;
                    else if (cartonInfo.packageNumber.Contains("围板箱"))
                        cartonInfo.packageType = 2;
                    else
                        cartonInfo.packageType = 0;
                    if (dtBox.Rows[0]["reserved7"].ToString().Trim() == "1") //上传EAS标志
                    {
                        return "Err:" + "重复上传!" + boxId;
                    }
                }
                else
                {
                    return "Err:" + "数据库中没有此箱标的记录!" + boxId;
                }
                //if (dtBag.Rows.Count > 0)
                //{
                //    for (int i = 0; i < dtBag.Rows.Count; i++)
                //    {
                //        cartonInfo.detail.Add(dtBag.Rows[i]["uid"].ToString().Trim()); //袋标
                //    }
                //}
                //else
                //{
                //    return "Err:" + "数据库中此箱标绑定的袋标记录!" + boxId;
                //}
            }
            catch (Exception ex)
            {
                return "Err:" + ex.Message;
            }

            try
            {
                string para = JsonConvert.SerializeObject(cartonInfo);
                string action = "{\"fun\":\"Import_CartonInfo\",\"prms\":" + para + "}";
                string result = HttpPostAction(action);

                Result r = JsonConvert.DeserializeObject<Result>(result.Replace("\"{", "{").Replace("\\\"", "\"").Replace("}\"", "}"));
                if (r.flage == 1)
                {
                    SqlSugarHelper.UpdateRecord<saveddata>(String.Format("uid='{0}'", boxId),
                       new Dictionary<string, object>() { { "reserved7", "1" } }); //上传EAS标志
                }
                else
                {
                    return "Err:" + r.msg;
                }
                JavaScriptSerializer jss = new JavaScriptSerializer();
                return jss.Serialize(r);
            }
            catch (Exception ex)
            {
                return "Err:" + ex.Message;
            }
        }

        /// <summary>
        /// 2.45 获取箱号信息
        /// </summary>
        /// <param name="cartonNumber"></param>
        public static string GetCartonInfo(string cartonNumber = "X2C322050600009")
        {
            try
            {
                string action = "{\"fun\":\"GetCartonInfo\",\"prms\":{\"cartonNumber\":\"" + cartonNumber + "\"}}";
                string uid = "123";
                string token = GetToken();

                // 时间搓
                TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                long timespan = Convert.ToInt64(ts.TotalSeconds);
                string orgdata = action + uid + timespan + token;

                // 获取hash码
                string sign = RSAHelper.XMLSign(orgdata, PrivateKey);
                Dictionary<string, string> header = new Dictionary<string, string>();
                header.Add("uid", uid);
                header.Add("token", token);
                header.Add("timespan", timespan.ToString());
                header.Add("sign", sign);
                Console.WriteLine(action);
                string result = HttpPost(header, apiUrl, action);

                //Console.WriteLine(result.Replace(",", ",\r\n"));
                return result;
                //MessageBox.Show(result);
            }
            catch (WebException we)
            {
                if (we.Response != null)
                {
                    Stream stream = we.Response.GetResponseStream();
                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                    string value = reader.ReadToEnd();
                    MessageBox.Show(value, "Ex");
                }
            }
            catch (Exception ex)
            {
                Exception src = ex.GetBaseException();
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
            return "";
        }


        public class Rootobject
        {
            public string fun { get; set; }
            public Prms prms { get; set; }
        }
        public class Prms
        {
            public string carNumber { get; set; }
        }
        public class RootBatchInfo
        {
            public string FNUMBER { get; set; }
            public int CFBATCHTYPE { get; set; }
            public string FCREATETIME { get; set; }
        }

        public static void GetManufacturebatch()
        {
            Rootobject root = new Rootobject();
            root.fun = "GetManufacturebatch";
            root.prms = new Prms();
            root.prms.carNumber = "";
            string action = JsonConvert.SerializeObject(root);
            //SQLLog.DBLog(action);
            try
            {
                string result = HttpPostAction(action);
                result = result.Replace("\\", "").
                                Replace("\"[", "[").
                                Replace("]\"", "]").
                                Replace("\"null\"", "");
                List<RootBatchInfo> carInfo = JsonConvert.DeserializeObject<List<RootBatchInfo>>(result);
                int nSysCount = 0;
                foreach (var item in carInfo)
                {
                    if ( /*1 == item.CFBATCHTYPE ||*/ item.FNUMBER.StartsWith("YN-A") || item.FNUMBER.StartsWith("YN-B") || item.FNUMBER.StartsWith("YN-C")
                        || item.FNUMBER.StartsWith("YN-D") || item.FNUMBER.StartsWith("YNH"))
                    {
                        int nRet = 0;
                        //string strRet = string.Format("if  not exists (select * from EASBatch  where Batch='{0}') Insert Into EASBatch (Batch,[type],CreateAt) Values('{1}',{2},'{3}')",
                        //                        item.FNUMBER,
                        //                        item.FNUMBER,
                        //                        item.CFBATCHTYPE,
                        //                        item.FCREATETIME);
                        //int nRet = DbHelperSQL.ExecuteSql(strRet);
                        EASBatch easBatch = SqlSugarHelper.Query<EASBatch>(
                            String.Format("Batch='{0}'", item.FNUMBER), "CreateAt");
                        if (easBatch == null)
                        {
                            easBatch = new EASBatch();
                            easBatch.Batch = item.FNUMBER;
                            easBatch.type = item.CFBATCHTYPE.ToString();
                            easBatch.CreateAt = item.FCREATETIME;
                            nRet = SqlSugarHelper.InsertRecord<EASBatch>(easBatch);
                        }
                        if (nRet > 0)
                            nSysCount++;
                    }
                }
                // return string.Format("查到{0}条记录,已同步", nSysCount);
            }
            catch (Exception ex)
            {
                throw ex;
                // return "Err:" + ex.Message;
            }
        }

        public static void Test()
        {
            try
            {
                string action = "{\"fun\":\"ApiTest\",\"prms\":[]}";
                string uid = "123";
                string token = GetToken();

                // 时间搓
                TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                long timespan = Convert.ToInt64(ts.TotalSeconds);
                //timespan = 1594883862103;
                //token = "";
                string orgdata = action + uid + timespan + token;

                // 获取hash码
                string sign = RSAHelper.XMLSign(orgdata, PrivateKey);
                Dictionary<string, string> header = new Dictionary<string, string>();
                header.Add("uid", uid);
                header.Add("token", token);
                header.Add("timespan", timespan.ToString());
                header.Add("sign", sign);
                string result = HttpPost(header, apiUrl, action);
                MessageBox.Show(result, "ok");
            }
            catch (WebException we)
            {
                if (we.Response != null)
                {
                    Stream stream = we.Response.GetResponseStream();
                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                    string value = reader.ReadToEnd();
                    MessageBox.Show(value, "Ex");
                }
            }
            catch (Exception ex)
            {
                Exception src = ex.GetBaseException();
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }

        private static string GetToken()
        {
            string action = "{\"fun\":\"GetToken\",\"prms\":{}}";
            string uid = "123";
            string token = "";
            // 时间搓
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            long timespan = Convert.ToInt64(ts.TotalSeconds);
            string orgdata = action + uid + timespan + token;

            // 获取hash码
            string sign = RSAHelper.XMLSign(orgdata, PrivateKey);

            Dictionary<string, string> header = new Dictionary<string, string>();
            header.Add("uid", uid);
            header.Add("token", token);
            header.Add("timespan", timespan.ToString());
            header.Add("sign", sign);
            string result = HttpPost(header, apiUrl, action);
            result = RSAHelper.XMLRSADecrypt(PrivateKey, result.Trim('\"'));
            Console.WriteLine("Token:" + result);
            return result;
        }

        /// 后台发送POST请求
        /// <summary>
        /// <param name="url">服务器地址</param>
        /// <param name="data">发送的数据</param>
        /// <returns></returns>
        private static string HttpPost(Dictionary<string, string> header, string url, string data)
        {
            //创建post请求
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Proxy = null;
            request.Method = "POST";
            foreach (string key in header.Keys)
            {
                request.Headers.Add(key, header[key]);
            }
            request.ContentType = "application/json;charset=UTF-8";
            byte[] payload = Encoding.UTF8.GetBytes(data);
            request.ContentLength = payload.Length;

            //发送post的请求
            Stream writer = request.GetRequestStream();
            writer.Write(payload, 0, payload.Length);
            writer.Close();

            //接受返回来的数据
            //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //Stream stream = response.GetResponseStream();
            //StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            //string value = reader.ReadToEnd();
            string value = GetResponseStringJson((HttpWebResponse)request.GetResponse());

            //reader.Close();
            //stream.Close();
            //response.Close();

            return value;
        }

        public static string HttpPostAction(string action)
        {
            try
            {
                string uid = Uid;
                string token = GetToken();

                // 时间搓
                TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                long timespan = Convert.ToInt64(ts.TotalSeconds);
                string orgdata = action + uid + timespan + token;

                // 获取hash码
                string sign = RSAHelper.XMLSign(orgdata, PrivateKey);
                Dictionary<string, string> header = new Dictionary<string, string>();
                header.Add("uid", uid);
                header.Add("token", token);
                header.Add("timespan", timespan.ToString());
                header.Add("sign", sign);
                string result = HttpPost(header, apiUrl, action);
                return result;
            }
            catch (WebException we)
            {
                //if (we.Response != null)
                //{
                //    Stream stream = we.Response.GetResponseStream();
                //    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                //    string value = reader.ReadToEnd();
                //    //MessageBox.Show(value, "Ex");
                //    return value;
                //}
                throw we;
            }
            catch (Exception ex)
            {
                // Exception src = ex.GetBaseException();
                // MessageBox.Show(ex.Message + ex.StackTrace);
                //return ex.Message;
                throw ex;
            }
        }

        /// <summary>  
        /// 返回List集合对象  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="JsonStr"></param>  
        /// <returns></returns>  
        public static List<T> JSONStringToList<T>(string JsonStr)
        {
            //使用JavaScriptSerializer()方式转json，需要添加System.Web.Extensions.dll
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            List<T> objs = Serializer.Deserialize<List<T>>(JsonStr);
            return objs;
        }

        public static Code GetNewCode(string number)
        {
            Code code = new Code();
            code.number = number;
            return code;
        }

        public static string GetResponseStringJson(HttpWebResponse webResponse)
        {
            using (Stream s = webResponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(s, Encoding.UTF8);
                string resp = reader.ReadToEnd();//Regex.Unescape(resp);

                JsonReader readerJson = new JsonTextReader(new StringReader(resp)); //针对转义字符特殊处理
                while (readerJson.Read())
                {
                    resp = readerJson.Value.ToString();
                }
                readerJson.Close();
                reader.Close();
                return resp;
            }
        }
    }
}
